<template>
  <n-modal
    :show="props.visible"
    preset="card"
    :title="props.data?.menuId ? '修改菜单' : '添加菜单'"
    style="width: 640px"
    @after-enter="handleOpen"
    @close="handleClose"
  >
    <n-form ref="formRef" :model="form" label-placement="left" :rules="rules">
      <n-form-item label="上级菜单">
        <n-tree-select
          v-model:value="form.parentId"
          :loading="treeSelectLoading"
          :options="treeSelectData"
          :default-value="0"
          label-field="menuName"
          key-field="menuId"
          @update:value="handleUpdateValue"
        />
      </n-form-item>

      <n-form-item label="菜单类型">
        <n-radio-group v-model:value="form.menuType">
          <n-radio value="M">目录</n-radio>
          <n-radio value="C">菜单</n-radio>
          <n-radio value="F">按钮</n-radio>
        </n-radio-group>
      </n-form-item>

      <n-form-item v-if="form.menuType != 'F'" label="菜单图标">
        <n-input v-model:value="form.icon" placeholder="请输入菜单图标" clearable />
      </n-form-item>

      <n-grid cols="2" :x-gap="30">
        <n-form-item-gi label="菜单名称" path="menuName">
          <n-input v-model:value="form.menuName" placeholder="请输入菜单名称" clearable />
        </n-form-item-gi>

        <n-form-item-gi label="显示排序" path="orderNum">
          <n-input-number v-model:value="form.orderNum" placeholder="请输入显示排序" clearable />
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType != 'F'" label="是否外链">
          <n-radio-group v-model:value="form.isFrame">
            <n-radio value="1">否</n-radio>
            <n-radio value="0">是</n-radio>
          </n-radio-group>
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType != 'F'" label="路由地址" path="path">
          <n-input v-model:value="form.path" placeholder="请输入路由地址" clearable />
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType == 'C'" label="组件路径" path="component">
          <n-input v-model:value="form.component" placeholder="请输入组件路径" clearable />
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType != 'M'" label="权限字符" path="perms">
          <n-input v-model:value="form.perms" placeholder="请输入权限标识" clearable />
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType == 'C'" label="路由参数" path="queryParam">
          <n-input v-model:value="form.queryParam" placeholder="路由参数" clearable />
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType == 'C'" label="是否缓存">
          <n-radio-group v-model:value="form.isCache">
            <n-radio value="1">否</n-radio>
            <n-radio value="0">是</n-radio>
          </n-radio-group>
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType != 'F'" label="显示状态">
          <n-radio-group v-model:value="form.visible">
            <n-radio value="0">显示</n-radio>
            <n-radio value="1">隐藏</n-radio>
          </n-radio-group>
        </n-form-item-gi>

        <n-form-item-gi v-if="form.menuType != 'F'" label="菜单状态">
          <n-radio-group v-model:value="form.status">
            <n-radio value="0">正常</n-radio>
            <n-radio value="1">停用</n-radio>
          </n-radio-group>
        </n-form-item-gi>
      </n-grid>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" @click="submitCallback" :loading="loading" :disabled="loading">
          确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { useMessage, type FormInst, type TreeSelectOption } from 'naive-ui';
import { reactive, ref, useTemplateRef } from 'vue';
import { addMenu, getMenuList, updateMenu } from '@/apis/system/menu';
import { handleTree } from '@/utils';

const emits = defineEmits(['close']);
const props = defineProps<{ visible: boolean; data: any }>();
const formRef = useTemplateRef<FormInst>('formRef');
const loading = ref(false);
const form = reactive({
  parentId: 0,
  menuType: 'M',
  icon: '',
  menuName: '',
  orderNum: null,
  isFrame: '1', // 是否外链 0:是 1:否
  isCache: '1', // 是否缓存 0:是 1:否
  path: '', // 路由地址
  component: '', // 组件路径
  perms: '', // 权限字符
  queryParam: '', // 路由参数
  visible: '0', // 显示状态 0:显示 1:隐藏
  status: '0', // 菜单状态 0:正常 1:停用
});
const treeSelectData: any = ref([]);
const treeSelectLoading = ref(false);
const message = useMessage();
const rules = ref({
  menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, type: 'number', message: '菜单顺序不能为空', trigger: 'blur' }],
  path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
});

const getTreeselect = async () => {
  treeSelectLoading.value = true;
  try {
    treeSelectData.value = [];
    const menu: any = { menuId: 0, menuName: '主类目', children: [] };
    const { data } = await getMenuList();
    menu.children = handleTree(data, 'menuId');
    treeSelectData.value.push(menu);
  } catch (error) {
  } finally {
    treeSelectLoading.value = false;
  }
};

const handleOpen = () => {
  getTreeselect();
  if (props.data) {
    Object.assign(form, props.data);
  }
};

const handleClose = (needRefresh = false) => {
  emits('close', { needRefresh });
};

const submitCallback = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (errors) {
      return;
    }
    loading.value = true;
    try {
      let res: any;
      if (props.data?.menuId !== undefined) {
        res = await updateMenu(form);
      } else {
        res = await addMenu(form);
      }
      if (res.code == 200) {
        message.success(props.data?.menuId !== undefined ? '修改成功' : '添加成功');
        handleClose(true);
      }
    } catch (error) {
    } finally {
      loading.value = false;
    }
  });
};

function handleUpdateValue(
  value: string | number | Array<string | number> | null,
  option: TreeSelectOption | null | Array<TreeSelectOption | null>,
) {
  console.log(value, option);
}
</script>

<style lang="less" scoped></style>
